﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;

namespace program
{
   
    public partial class print : Form
    {

        public ImageList MyList = new ImageList();
        public int test = 0;
        public string leftMargin, rightMargin, topMargin, downMargin;

        //PrintDocument MyDocument = new PrintDocument();
        //PrintDialog dlg1 = new PrintDialog();

        List<MyImage> MyImages = new List<MyImage>();
        List<MyGroup> MyGroups = new List<MyGroup>();

        public print()
        {

            InitializeComponent();
            rightMargin = leftMargin = topMargin = downMargin = "10";

        }

        public void SaveMyFile(string path)
        {
            FileStream fs = new FileStream(path, FileMode.Create);
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(fs, this.MyGroups);
            formatter.Serialize(fs, this.MyImages);
            fs.Close();
        }

        public void  OpenMyFile(string path)
        {
            FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            BinaryFormatter b = new BinaryFormatter();
            this.MyGroups = b.Deserialize(fileStream) as List<MyGroup>;
            this.MyImages = b.Deserialize(fileStream) as List<MyImage>;
            fileStream.Close();
        }

        private void 打开ToolStripMenuItem1_Click_1(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "打开";
            dlg.ShowReadOnly = false;
            dlg.CheckFileExists = true;
            dlg.CheckPathExists = true;
            dlg.ValidateNames = true;
            dlg.Multiselect = true;
            string dir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            dlg.InitialDirectory = dir;
            dlg.Filter = "jpg文件 |*.jpg| bmp文件 |*.bmp";

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                listView1.LargeImageList = MyList;
                MyList.ImageSize = new Size(254, 178);
                listView1.View = View.LargeIcon;
                int i = 0;

                MyImages.Clear();
                MyGroups.Clear();
                MyList.Images.Clear();
                listView1.Clear();
                foreach (string strFilename in dlg.FileNames)
                {
                    MyList.Images.Add(Image.FromFile(strFilename));
                    MyImage _image = new MyImage();
                    int tmp = strFilename.LastIndexOf('\\');
                    listView1.Items.Add((i+1).ToString()+". "+strFilename.Substring(tmp+1));
                    _image.set(strFilename, (i + 1).ToString() + "." + strFilename.Substring(tmp + 1), i, 
                        Image.FromFile(strFilename).PhysicalDimension.Width,Image.FromFile(strFilename).PhysicalDimension.Height);
                    listView1.Items[i].ImageIndex = i++;
                    MyImages.Add(_image);


                    ////test
                    //MyGroup _group = new MyGroup();
                    //_group.set(_image, _image);
                    //MyGroups.Add(_group);
                }
                MyImage up = null;
                int judge = 0;
                foreach (MyImage _image in MyImages)
                {
                  

                    if ((judge % 2 == 0)&&(judge != MyImages.Count-1))
                    {
                        up = _image;
                        judge++;
                    }
                    else if ((judge % 2 == 0) && (judge == MyImages.Count - 1))
                    {
                        MyGroup _group = new MyGroup();
                        _group.set(_image,null);
                        MyGroups.Add(_group);
                        judge++;
                    }
                    else
                    {

                        MyGroup _group = new MyGroup();
                        _group.set(up, _image);
                        MyGroups.Add(_group);
                        judge++;
                    }
                }
             
            }
           }

        private void 保存ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Title = "另存为";
            dlg.Filter = "制卷文件|*.ptr";
            dlg.DefaultExt = "ptr";
        
            dlg.CheckPathExists = true;
            dlg.ValidateNames = true;
            dlg.FileName = "new";
            //some mode
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                this.SaveMyFile(dlg.FileName.ToString());
            }

        }
        //页面设置
        private void 打印ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //pageSetupDialog1.Document = MyDocument;
            //pageSetupDialog1.AllowMargins = true;
            //pageSetupDialog1.AllowOrientation = true;
            //pageSetupDialog1.AllowPaper = true;
            //pageSetupDialog1.AllowPrinter = true;
            MyDocument.DefaultPageSettings.PaperSize = new PaperSize("A4", 827, 1169);
            Setting mySetting = new Setting(this);
            mySetting.ShowDialog();
           // pageSetupDialog1.ShowDialog();
        }
        //打印机
        private void 打印ToolStripMenuItem1_Click(object sender, EventArgs e)
        {

           this.printDialog1.Document = MyDocument;
           this.printDialog1.AllowCurrentPage = true;
           this.printDialog1.AllowPrintToFile = false;
           this.printDialog1.AllowSelection = true;
           this.printDialog1.AllowSomePages = true;
           if (this.printDialog1.ShowDialog() == DialogResult.OK)
           {
               MyDocument.DocumentName = MyGroups.Count.ToString();
               MyDocument.DefaultPageSettings.PrinterSettings.Collate = true;
               if (MyGroups.Count == 0)
               {
                   MessageBox.Show("没有图片");
               }
               else
               {
                   int count = MyGroups.Count;
                   for (int i = 0; i < count; i++)
                   {
                       //MyDocument.DefaultPageSettings.PrinterSettings.FromPage = i+1 ;
                       //MyDocument.PrinterSettings.FromPage = i + 1;
                       MyDocument.Print();
                       
                   }
               }
           }
        }

        private void MyDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            //获取打印机分辨率
            //int PrinterWidth = MyDocument.DefaultPageSettings.PrinterResolution.X;
            //int PrinterHeight = MyDocument.DefaultPageSettings.PrinterResolution.Y;
            float TrueWidth =  0f;
            float TrueHeight = 0f;
            //保证图片为5寸
            TrueWidth = 127f * (this.MyDocument.DefaultPageSettings.PaperSize.Width) / 210f;
            TrueHeight = 88.9f * (this.MyDocument.DefaultPageSettings.PaperSize.Height) / 297f;
            float upyPosition = Single.Parse(topMargin.Trim()) * (this.MyDocument.DefaultPageSettings.PaperSize.Height) / 297f;
            float upxPosition = Single.Parse(leftMargin.Trim()) * (this.MyDocument.DefaultPageSettings.PaperSize.Width) / 210f;
            float downxPosition = upxPosition;
            float space = 10f * (this.MyDocument.DefaultPageSettings.PaperSize.Height) / 297f;
            float downyPosition = MyDocument.DefaultPageSettings.PaperSize.Height -
                Single.Parse(downMargin.Trim()) * (this.MyDocument.DefaultPageSettings.PaperSize.Height) / 297f - 2*space-TrueHeight;


            //if (test < MyGroups.Count - 1)
            //{
            //    e.HasMorePages = true;
            //}
            //else e.HasMorePages = false;
           //// MessageBox.Show(e.PageSettings.PrinterSettings.FromPage.ToString());
           // MyDocument.DefaultPageSettings.PrinterSettings.FromPage = test + 1;
           // e.Cancel = true;
           
            StringFormat format = new StringFormat();     
            format.LineAlignment = StringAlignment.Center;
            format.Alignment = StringAlignment.Center;
            format.Trimming = StringTrimming.EllipsisCharacter;
            
           
            RectangleF uprect = new RectangleF(upxPosition, upyPosition + TrueHeight + space, TrueWidth, 2*space);
            RectangleF downrect = new RectangleF(upxPosition, downyPosition + TrueHeight + space, TrueWidth, 2*space);

            e.Graphics.DrawImage(Image.FromFile(MyGroups[test].UpImage.path),upxPosition,upyPosition,TrueWidth, TrueHeight);
            e.Graphics.DrawString(MyGroups[test].UpImage.name, new Font("宋体", 12), Brushes.Black, uprect, format);
            if (MyGroups[test].DownImage != null)
            {
                e.Graphics.DrawImage(Image.FromFile(MyGroups[test].DownImage.path), downxPosition, downyPosition, TrueWidth, TrueHeight);
                e.Graphics.DrawString(MyGroups[test].DownImage.name, new Font("宋体", 23), Brushes.Black, downrect, format);
            }
            
            test++;

        }

        private void 打印ToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            Thread MyThread;
            MyThread = new Thread(new ThreadStart(MyDocument.Print));
            MyThread.Start();
            MyThread.Abort();
           //MyDocument.Print();
        }

        private void 打开文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {

             OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "打开文件";
            dlg.ShowReadOnly = false;
            dlg.CheckFileExists = true;
            dlg.CheckPathExists = true;
            dlg.ValidateNames = true;
            string dir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            dlg.InitialDirectory = dir;
            dlg.Filter = "制卷文件 |*.ptr";


            listView1.LargeImageList = MyList;
            MyList.ImageSize = new Size(254, 178);
            listView1.View = View.LargeIcon;

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                this.OpenMyFile(dlg.FileName.ToString());

                for (int i = 0; i < MyImages.Count; i++)
                {

                    MyList.Images.Add(Image.FromFile(MyImages[i].path));
                    listView1.Items.Add(MyImages[i].name);
                    listView1.Items[i].ImageIndex = i;
                }
            }
     
            }

        private void MyDocument_BeginPrint(object sender, PrintEventArgs e)
        {

        }

        private void MyDocument_EndPrint(object sender, PrintEventArgs e)
        {
                 if(test == MyGroups.Count)
                {              
                    test = 0;
                }

      
        }
    }
}
